package org.ruanjj.io;

import org.junit.Test;
import java.io.*;


public class FileReaderWriterMain {
    public static void main(String[] args) {
        File a = new File("abc.txt");
        try(FileReader fileReader = new FileReader(a)){
            //1.
            int data;
            while((data = fileReader.read()) != -1){
                System.out.print((char) data);
            }

            System.out.println("\n===================================");

            //2.
            char[] res = new char[5];
            int len;
            while((len = fileReader.read(res)) != -1) {
                for (int i=0; i<len; i++) {
                    System.out.print(res[i]);
                }
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void testWriter(){
        File a = new File("info.txt");
        try(FileWriter fileWriter = new FileWriter(a)) {
            fileWriter.write("I like Java!!!\n");
            fileWriter.write("Java don't like me\n");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void test(){
        File srcFile = new File("info.txt");
        File dirFile = new File("info_copy.txt");

        try(
                FileReader fr = new FileReader(srcFile);
                FileWriter fw = new FileWriter(dirFile)
                ){
            char[] CBuffer = new char[5];
            int len;
            while((len = fr.read(CBuffer)) != -1){
                fw.write(CBuffer,0,len);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
